<template>
  <view class="modal-overlay" v-if="show" @click="handleClose">
    <view class="modal-content" @click.stop>
      <view class="modal-header">
        <text class="modal-title">导出日记</text>
        <view class="close-btn" @click="handleClose">
          <uni-icons type="close" size="20" color="#666"></uni-icons>
        </view>
      </view>
      
      <view class="export-options">
        <!-- 导出格式 -->
        <view class="option-section">
          <text class="section-label">导出格式</text>
          <view class="format-options">
            <view 
              class="format-item" 
              v-for="format in formatOptions" 
              :key="format.value"
              :class="{ active: selectedFormat === format.value }"
              @click="selectFormat(format.value)"
            >
              <view class="format-icon" :style="{ backgroundColor: format.color + '20' }">
                <uni-icons :type="format.icon" size="20" :color="format.color"></uni-icons>
              </view>
              <view class="format-info">
                <text class="format-name">{{ format.name }}</text>
                <text class="format-desc">{{ format.description }}</text>
              </view>
              <view class="format-check" v-if="selectedFormat === format.value">
                <uni-icons type="checkmarkempty" size="16" color="#1890ff"></uni-icons>
              </view>
            </view>
          </view>
        </view>
        
        <!-- 时间范围 -->
        <view class="option-section">
          <text class="section-label">时间范围</text>
          <view class="date-range">
            <view class="date-item" @click="showStartDatePicker = true">
              <text class="date-label">开始日期</text>
              <text class="date-value">{{ startDate || '选择日期' }}</text>
              <uni-icons type="calendar" size="16" color="#666"></uni-icons>
            </view>
            <view class="date-separator">
              <text class="separator-text">至</text>
            </view>
            <view class="date-item" @click="showEndDatePicker = true">
              <text class="date-label">结束日期</text>
              <text class="date-value">{{ endDate || '选择日期' }}</text>
              <uni-icons type="calendar" size="16" color="#666"></uni-icons>
            </view>
          </view>
          
          <!-- 快捷选择 -->
          <view class="quick-select">
            <view 
              class="quick-item" 
              v-for="quick in quickRanges" 
              :key="quick.value"
              @click="selectQuickRange(quick)"
            >
              <text class="quick-text">{{ quick.label }}</text>
            </view>
          </view>
        </view>
        
        <!-- 筛选条件 -->
        <view class="option-section">
          <text class="section-label">筛选条件</text>
          
          <!-- 分类筛选 -->
          <view class="filter-item">
            <text class="filter-label">分类</text>
            <view class="filter-content" @click="showCategoryFilter = true">
              <text class="filter-value" :class="{ placeholder: !selectedCategories.length }">
                {{ selectedCategoriesText || '全部分类' }}
              </text>
              <uni-icons type="right" size="16" color="#ccc"></uni-icons>
            </view>
          </view>
          
          <!-- 标签筛选 -->
          <view class="filter-item">
            <text class="filter-label">标签</text>
            <view class="filter-content" @click="showTagFilter = true">
              <text class="filter-value" :class="{ placeholder: !selectedTags.length }">
                {{ selectedTagsText || '全部标签' }}
              </text>
              <uni-icons type="right" size="16" color="#ccc"></uni-icons>
            </view>
          </view>
        </view>
        
        <!-- 导出预览 -->
        <view class="preview-section">
          <text class="section-label">导出预览</text>
          <view class="preview-info">
            <view class="preview-item">
              <text class="preview-label">预计导出</text>
              <text class="preview-value">{{ estimatedCount }} 篇日记</text>
            </view>
            <view class="preview-item">
              <text class="preview-label">文件大小</text>
              <text class="preview-value">约 {{ estimatedSize }}</text>
            </view>
          </view>
        </view>
      </view>
      
      <view class="modal-footer">
        <button class="cancel-btn" @click="handleClose">取消</button>
        <button class="export-btn" :disabled="!canExport" @click="handleExport">
          <uni-icons type="download" size="16" color="#ffffff" v-if="!exporting"></uni-icons>
          <uni-icons type="spinner-cycle" size="16" color="#ffffff" v-else></uni-icons>
          <text class="btn-text">{{ exporting ? '导出中...' : '开始导出' }}</text>
        </button>
      </view>
      
      <!-- 日期选择器 -->
      <picker 
        mode="date" 
        :value="startDate"
        @change="onStartDateChange"
        v-if="showStartDatePicker"
      ></picker>
      
      <picker 
        mode="date" 
        :value="endDate"
        @change="onEndDateChange"
        v-if="showEndDatePicker"
      ></picker>
      
      <!-- 分类筛选弹窗 -->
      <CategoryFilterModal
        v-model:show="showCategoryFilter"
        :categories="categories"
        :selected="selectedCategories"
        @confirm="onCategoryConfirm"
      />
      
      <!-- 标签筛选弹窗 -->
      <TagFilterModal
        v-model:show="showTagFilter"
        :tags="tags"
        :selected="selectedTags"
        @confirm="onTagConfirm"
      />
    </view>
  </view>
</template>

<script>
import { exportDiariesAPI } from '@/api/statistics'
import { getCategoriesAPI } from '@/api/category'
import { getTagsAPI } from '@/api/tag'
import { formatDate } from '@/utils/index'

export default {
  name: 'ExportModal',
  props: {
    show: {
      type: Boolean,
      default: false
    }
  },
  emits: ['update:show', 'success'],
  data() {
    return {
      exporting: false,
      selectedFormat: 'pdf',
      startDate: '',
      endDate: '',
      selectedCategories: [],
      selectedTags: [],
      
      showStartDatePicker: false,
      showEndDatePicker: false,
      showCategoryFilter: false,
      showTagFilter: false,
      
      categories: [],
      tags: [],
      
      formatOptions: [
        {
          value: 'pdf',
          name: 'PDF文档',
          description: '适合打印和阅读',
          icon: 'compose',
          color: '#ff4d4f'
        },
        {
          value: 'json',
          name: 'JSON数据',
          description: '包含完整数据结构',
          icon: 'gear',
          color: '#1890ff'
        },
        {
          value: 'txt',
          name: '纯文本',
          description: '简洁的文本格式',
          icon: 'compose',
          color: '#52c41a'
        }
      ],
      
      quickRanges: [
        {
          label: '最近一周',
          value: 'week',
          days: 7
        },
        {
          label: '最近一月',
          value: 'month',
          days: 30
        },
        {
          label: '最近三月',
          value: 'quarter',
          days: 90
        },
        {
          label: '最近一年',
          value: 'year',
          days: 365
        }
      ]
    }
  },
  computed: {
    canExport() {
      return this.startDate && this.endDate && !this.exporting
    },
    
    selectedCategoriesText() {
      if (!this.selectedCategories.length) return ''
      if (this.selectedCategories.length === this.categories.length) return '全部分类'
      return this.selectedCategories.map(id => {
        const category = this.categories.find(c => c.id === id)
        return category ? category.name : ''
      }).join(', ')
    },
    
    selectedTagsText() {
      if (!this.selectedTags.length) return ''
      if (this.selectedTags.length === this.tags.length) return '全部标签'
      return this.selectedTags.map(id => {
        const tag = this.tags.find(t => t.id === id)
        return tag ? tag.name : ''
      }).join(', ')
    },
    
    estimatedCount() {
      // 这里应该根据筛选条件计算预计导出的日记数量
      return 0
    },
    
    estimatedSize() {
      // 根据格式和数量估算文件大小
      const baseSize = this.estimatedCount * 2 // 每篇日记约2KB
      if (this.selectedFormat === 'pdf') {
        return this.formatFileSize(baseSize * 3)
      } else if (this.selectedFormat === 'json') {
        return this.formatFileSize(baseSize * 1.5)
      } else {
        return this.formatFileSize(baseSize)
      }
    }
  },
  watch: {
    show(newVal) {
      if (newVal) {
        this.initModal()
      }
    }
  },
  methods: {
    async initModal() {
      // 设置默认时间范围（最近一月）
      const now = new Date()
      const oneMonthAgo = new Date(now.getTime() - 30 * 24 * 60 * 60 * 1000)
      
      this.endDate = formatDate(now)
      this.startDate = formatDate(oneMonthAgo)
      
      // 加载分类和标签数据
      await this.loadFiltersData()
    },
    
    async loadFiltersData() {
      try {
        const [categoriesRes, tagsRes] = await Promise.all([
          getCategoriesAPI(),
          getTagsAPI()
        ])
        
        this.categories = categoriesRes.data || []
        this.tags = tagsRes.data || []
        
      } catch (error) {
        console.error('加载筛选数据失败:', error)
      }
    },
    
    selectFormat(format) {
      this.selectedFormat = format
    },
    
    selectQuickRange(range) {
      const now = new Date()
      const startDate = new Date(now.getTime() - range.days * 24 * 60 * 60 * 1000)
      
      this.endDate = formatDate(now)
      this.startDate = formatDate(startDate)
    },
    
    onStartDateChange(e) {
      this.startDate = e.detail.value
      this.showStartDatePicker = false
    },
    
    onEndDateChange(e) {
      this.endDate = e.detail.value
      this.showEndDatePicker = false
    },
    
    onCategoryConfirm(categories) {
      this.selectedCategories = categories
    },
    
    onTagConfirm(tags) {
      this.selectedTags = tags
    },
    
    async handleExport() {
      if (!this.canExport) return
      
      this.exporting = true
      
      try {
        const params = {
          format: this.selectedFormat,
          startDate: this.startDate,
          endDate: this.endDate,
          categoryIds: this.selectedCategories,
          tagIds: this.selectedTags
        }
        
        const res = await exportDiariesAPI(params)
        
        // 处理导出结果
        if (res.data.downloadUrl) {
          // 下载文件
          uni.downloadFile({
            url: res.data.downloadUrl,
            success: (downloadRes) => {
              if (downloadRes.statusCode === 200) {
                uni.showToast({
                  title: '导出成功',
                  icon: 'success'
                })
                this.$emit('success', downloadRes.tempFilePath)
                this.handleClose()
              }
            },
            fail: (error) => {
              console.error('下载失败:', error)
              uni.showToast({
                title: '下载失败',
                icon: 'none'
              })
            }
          })
        }
        
      } catch (error) {
        console.error('导出失败:', error)
        uni.showToast({
          title: '导出失败',
          icon: 'none'
        })
      } finally {
        this.exporting = false
      }
    },
    
    handleClose() {
      this.$emit('update:show', false)
    },
    
    formatFileSize(bytes) {
      if (bytes === 0) return '0 B'
      const k = 1024
      const sizes = ['B', 'KB', 'MB', 'GB']
      const i = Math.floor(Math.log(bytes) / Math.log(k))
      return parseFloat((bytes / Math.pow(k, i)).toFixed(1)) + ' ' + sizes[i]
    }
  }
}
</script>

<style scoped>
.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
}

.modal-content {
  width: 90%;
  max-width: 640rpx;
  max-height: 80%;
  background-color: #ffffff;
  border-radius: 24rpx;
  overflow: hidden;
  animation: modalShow 0.3s ease-out;
}

@keyframes modalShow {
  from {
    opacity: 0;
    transform: scale(0.9);
  }
  to {
    opacity: 1;
    transform: scale(1);
  }
}

.modal-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 32rpx;
  border-bottom: 1rpx solid #f0f0f0;
}

.modal-title {
  font-size: 32rpx;
  font-weight: 600;
  color: #333333;
}

.close-btn {
  width: 60rpx;
  height: 60rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 30rpx;
  background-color: #f8f8f8;
}

.export-options {
  max-height: 60vh;
  overflow-y: auto;
  padding: 32rpx;
}

.option-section {
  margin-bottom: 48rpx;
}

.option-section:last-child {
  margin-bottom: 0;
}

.section-label {
  display: block;
  font-size: 28rpx;
  font-weight: 600;
  color: #333333;
  margin-bottom: 24rpx;
}

.format-options {
  display: flex;
  flex-direction: column;
  gap: 16rpx;
}

.format-item {
  display: flex;
  align-items: center;
  padding: 24rpx;
  border: 2rpx solid #f0f0f0;
  border-radius: 16rpx;
  transition: all 0.3s;
}

.format-item.active {
  border-color: #1890ff;
  background-color: #f6ffed;
}

.format-icon {
  width: 64rpx;
  height: 64rpx;
  border-radius: 32rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 24rpx;
}

.format-info {
  flex: 1;
}

.format-name {
  display: block;
  font-size: 28rpx;
  font-weight: 500;
  color: #333333;
  margin-bottom: 8rpx;
}

.format-desc {
  font-size: 24rpx;
  color: #666666;
}

.format-check {
  width: 40rpx;
  height: 40rpx;
  border-radius: 20rpx;
  background-color: #1890ff;
  display: flex;
  align-items: center;
  justify-content: center;
}

.date-range {
  display: flex;
  align-items: center;
  gap: 16rpx;
  margin-bottom: 24rpx;
}

.date-item {
  flex: 1;
  display: flex;
  flex-direction: column;
  gap: 8rpx;
  padding: 24rpx;
  background-color: #f8f8f8;
  border-radius: 16rpx;
  position: relative;
}

.date-label {
  font-size: 24rpx;
  color: #666666;
}

.date-value {
  font-size: 28rpx;
  color: #333333;
  font-weight: 500;
}

.date-separator {
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 16rpx;
}

.separator-text {
  font-size: 24rpx;
  color: #666666;
}

.quick-select {
  display: flex;
  gap: 16rpx;
  flex-wrap: wrap;
}

.quick-item {
  padding: 16rpx 24rpx;
  background-color: #f0f0f0;
  color: #666666;
  border-radius: 20rpx;
  font-size: 24rpx;
  transition: all 0.3s;
}

.quick-item:active {
  background-color: #1890ff;
  color: #ffffff;
}

.filter-item {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 24rpx 0;
  border-bottom: 1rpx solid #f0f0f0;
}

.filter-item:last-child {
  border-bottom: none;
}

.filter-label {
  font-size: 28rpx;
  color: #333333;
  width: 120rpx;
}

.filter-content {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-left: 24rpx;
}

.filter-value {
  font-size: 28rpx;
  color: #333333;
}

.filter-value.placeholder {
  color: #999999;
}

.preview-section {
  background-color: #f8f8f8;
  border-radius: 16rpx;
  padding: 24rpx;
}

.preview-info {
  display: flex;
  justify-content: space-between;
}

.preview-item {
  text-align: center;
}

.preview-label {
  display: block;
  font-size: 24rpx;
  color: #666666;
  margin-bottom: 8rpx;
}

.preview-value {
  font-size: 28rpx;
  font-weight: 600;
  color: #333333;
}

.modal-footer {
  display: flex;
  gap: 24rpx;
  padding: 32rpx;
  border-top: 1rpx solid #f0f0f0;
}

.cancel-btn {
  flex: 1;
  height: 88rpx;
  background-color: #ffffff;
  border: 2rpx solid #d9d9d9;
  border-radius: 44rpx;
  font-size: 28rpx;
  color: #666666;
}

.cancel-btn::after {
  border: none;
}

.export-btn {
  flex: 2;
  height: 88rpx;
  background-color: #1890ff;
  border: none;
  border-radius: 44rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 16rpx;
  font-size: 28rpx;
  color: #ffffff;
}

.export-btn:disabled {
  background-color: #cccccc;
}

.export-btn::after {
  border: none;
}

.btn-text {
  font-size: 28rpx;
  color: #ffffff;
}
</style> 